package com.novoda.runbuddy;

import junit.framework.Test;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import positron.harness.DatabaseFixture;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.test.InstrumentationTestRunner;
import android.util.Log;

import com.novoda.runbuddy.provider.ContentProviderRouteTest;
import com.novoda.runbuddy.util.SqlScanner;

public class AllTests extends InstrumentationTestRunner {

	private DatabaseFixture	databaseFixture;
	private SQLiteDatabase		mDB;
	private static final String	RUN_BUDDY_DB	= "runBuddyDB1.db";

	public void onCreate(Bundle arg0) {
		databaseFixture = new DatabaseFixture(this);
		onStart();
		start();
	}

	public void onStart() {
		
		Log.i("TestRunner", "this is is start");
		databaseFixture.backup();
		getTargetContext().deleteDatabase(RUN_BUDDY_DB);
		mDB = getTargetContext().openOrCreateDatabase(RUN_BUDDY_DB, Context.MODE_WORLD_WRITEABLE, null);
		createDB();
		runTest();
		databaseFixture.restore();
		
		//junit.textui.ResultPrinter test;
		
		//this.finish(0, null);
	}
	
	public static Test suite() {
		TestSuite suite = new TestSuite();
		suite.addTestSuite(ContentProviderRouteTest.class);
		return suite;
	}
	
//	protected TestSuite suite() {
//		TestSuite suite = new TestSuite();
//		suite.addTestSuite(ContentProviderRouteTest.class);
//		return suite;
//	}

	public void runTest() {
		TestSuite suite = new TestSuite();
		suite.addTestSuite(ContentProviderRouteTest.class);
		// suite.addTestSuite(ContentProviderTestCase.class);
		TestResult ts = new TestResult();

		suite.run(ts);
		
		Log.i("Positron", ts.toString() + " " + suite.toString() + " " + this.toString());

	}

	/** Backup all databases in the tested application. */
	public void backup() {
		databaseFixture.backup();
	}

	/** Backup the given database. */
	public void backup(String database) {
		databaseFixture.backup(database);
	}

	/** Restore all databases in the tested application that have backups. */
	public void restore() {
		databaseFixture.restore();
	}

	public void createDB() {
		executeDB("db_create");
	}

	public void insertValuesIntoDB() {
		executeDB("positron_cp_route_insert");
	}

	public void dropValuesFromDB() {
		executeDB("db_drop");
	}

	public void executeDB(String resName) {
		SqlScanner insertDB = new SqlScanner(getContext().getResources().openRawResource(
				getContext().getResources().getIdentifier(resName, "raw", "com.novoda.runbuddy")));
		mDB.beginTransaction();
		while (insertDB.hasNext()) {
			mDB.execSQL(insertDB.next());
		}
		mDB.setTransactionSuccessful();
		mDB.endTransaction();
	}

	public void executeDB(int resId) {
		SqlScanner insertDB = new SqlScanner(getContext().getResources().openRawResource(resId));
		mDB.beginTransaction();
		while (insertDB.hasNext()) {
			mDB.execSQL(insertDB.next());
		}
		mDB.setTransactionSuccessful();
		mDB.endTransaction();
	}
}
